package com.jmhy.sdk.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.jmhy.sdk.common.JiMiSDK;
import com.jmhy.sdk.config.AppConfig;
import com.jmhy.sdk.http.ApiAsyncTask;
import com.jmhy.sdk.http.ApiRequestListener;
import com.jmhy.sdk.model.MobileUser;
import com.jmhy.sdk.model.Msg;
import com.jmhy.sdk.sdk.JmhyApi;
import com.jmhy.sdk.utils.FragmentUtils;
import com.jmhy.sdk.utils.Logger;
import com.jmhy.sdk.utils.TimeDownUtils;
import com.jmhy.sdk.utils.Utils;
import com.jmhy.sdk.view.VerifyCodeEditText;

import java.util.regex.Pattern;

/**
 * @author #Suyghur.
 * Created on 2021/05/06
 */
public class JmUserMobileLogin8Fragment extends JmBaseFragment implements View.OnClickListener {

    private static final int ACTION_BACK = 1000;
    private static final int ACTION_SEND = 1001;
    private static final int ACTION_LOGIN = 1002;

    private View view;
    private ImageView ivBack;
    private EditText etPhone;
    private VerifyCodeEditText vcSms;
    private Button btnLogin;


    private ApiAsyncTask smsTask;
    private ApiAsyncTask mobileLoginTask;

    private final Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 101:
                    //倒计时
                    changeTimeView((Integer) msg.obj);
                    break;
                case AppConfig.CODE_SUCCESS:
                    changeTimeNum();
                    String successMsg = (String) msg.obj;
                    showMsg(successMsg);
                    break;
                case AppConfig.CODE_FAIL:
                    if (TimeDownUtils.isRunning()) {
                        TimeDownUtils.cancel();
                        vcSms.getButton().setText(AppConfig.resourceId(getActivity(), "moblie_bt_code", "string"));
                        vcSms.getButton().setEnabled(true);
                    }
                    String failMsg = (String) msg.obj;
                    showMsg(failMsg);
                    break;
                case AppConfig.MOBILELOGIN_SUCCESS:
                    // 直接登录成功，返回数据
                    MobileUser mobileUser = (MobileUser) msg.obj;
                    Logger.d("mobile login success : " + mobileUser.toString());
                    if (mobileUser.getIs_reg() == 1) {
                        JiMiSDK.getStatisticsSDK().onRegister("JiMiSDK", true);
                    } else {
                        JiMiSDK.getStatisticsSDK().onLogin(mobileUser.getOpenid());
                    }
                    mSeference.saveAccount(mobileUser.getUnname(), "~~test", mobileUser.getLogin_token());
                    AppConfig.saveMap(mobileUser.getUnname(), "~~test", mobileUser.getLogin_token());
                    Utils.saveUserToSd(getActivity());
                    wrapaLoginInfo("success", mobileUser.getMessage(), mobileUser.getUnname(), mobileUser.getOpenid(), mobileUser.getGame_token());
                    showUserMsg(mobileUser.getUnname());
                    AppConfig.USERURL = Utils.toBase64url(mobileUser.getFloat_url_user_center());
                    String url = Utils.toBase64url(mobileUser.getShow_url_after_login());
                    if (TextUtils.isEmpty(url)) {
                        url = Utils.toBase64url(mobileUser.getShow_url_popup());
                    }
                    turnToNotice(url);
                    getActivity().finish();
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(AppConfig.resourceId(getActivity(), "jm_select_mobile_login_8", "layout"), container, false);
            initView(view);
        }
        return view;
    }

    private void initView(View view) {
        ivBack = view.findViewById(AppConfig.resourceId(getActivity(), "btn_reback", "id"));
        ivBack.setTag(ACTION_BACK);
        ivBack.setOnClickListener(this);

        etPhone = view.findViewById(AppConfig.resourceId(getActivity(), "et_input_phone", "id"));
        etPhone.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_CLASS_PHONE);

        vcSms = view.findViewById(AppConfig.resourceId(getActivity(), "et_input_sms", "id"));
        vcSms.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_CLASS_PHONE);
        vcSms.getButton().setTag(ACTION_SEND);
        vcSms.getButton().setOnClickListener(this);

        btnLogin = view.findViewById(AppConfig.resourceId(getActivity(), "btn_login", "id"));
        btnLogin.setTag(ACTION_LOGIN);
        btnLogin.setOnClickListener(this);

    }

    private boolean verifyPhoneNum(String num) {
        Pattern pattern = Pattern.compile("^[1]\\d{10}$");
        return !pattern.matcher(num).matches();
    }

    private void getVerifyCode() {
        String phoneNum = etPhone.getText().toString();
        if (TextUtils.isEmpty(phoneNum) || phoneNum.length() != 11) {
            sendData(AppConfig.CODE_FAIL, "请输入正确的手机号", mHandler);
            return;
        }
        if (verifyPhoneNum(phoneNum)) {
            sendData(AppConfig.CODE_FAIL, "请输入正确的手机号", mHandler);
            return;
        }
        smsTask = JmhyApi.get().startRequestSMS(getActivity(), AppConfig.appKey, phoneNum, "+86", "1", new ApiRequestListener() {
            @Override
            public void onSuccess(Object obj) {
                if (obj != null) {
                    Msg msg = (Msg) obj;
                    if (msg.getCode().equals("0")) {
                        sendData(AppConfig.CODE_SUCCESS, msg.getMessage(), mHandler);
                    } else {
                        sendData(AppConfig.CODE_FAIL, msg.getMessage(), mHandler);
                    }
                }
            }

            @Override
            public void onError(int statusCode) {
                sendData(AppConfig.CODE_FAIL, AppConfig.getString(getActivity(), "http_rror_msg"), mHandler);
            }
        });
    }

    private void callLoginOrRegister() {
        String phoneNum = etPhone.getText().toString();
        String smsNum = vcSms.getEditText().getText().toString();
        if (TextUtils.isEmpty(phoneNum) || phoneNum.length() != 11) {
            sendData(AppConfig.CODE_FAIL, "请输入正确的手机号", mHandler);
            return;
        }
        if (verifyPhoneNum(phoneNum)) {
            sendData(AppConfig.CODE_FAIL, "请输入正确的手机号", mHandler);
            return;
        }
        if (TextUtils.isEmpty(smsNum)) {
            sendData(AppConfig.CODE_FAIL, AppConfig.getString(getActivity(), "user_hintcode_msg"), mHandler);
            return;
        }
        mobileLoginTask = JmhyApi.get().startloginMoblie(getActivity(), AppConfig.appKey, phoneNum, "+86", smsNum, "1", new ApiRequestListener() {
            @Override
            public void onSuccess(Object obj) {
                if (obj != null) {
                    MobileUser mobileUser = (MobileUser) obj;
                    if (mobileUser.getCode().equals("0")) {
                        sendData(AppConfig.MOBILELOGIN_SUCCESS, obj, mHandler);
                    } else {
                        sendData(AppConfig.CODE_FAIL, mobileUser.getMessage(), mHandler);
                        JiMiSDK.reportRequestErrorAction(getActivity(), "sdk_phone_login_error", mobileUser.getCode(), mobileUser.getMessage());
                    }
                }
            }

            @Override
            public void onError(int statusCode) {
                sendData(AppConfig.CODE_FAIL, AppConfig.getString(getActivity(), "http_rror_msg"), mHandler);
            }
        });
    }

    private void changeTimeView(int time) {

        if (vcSms.getButton() == null) {
            return;
        }
        if (time <= 0) {
            vcSms.getButton().setText(AppConfig.resourceId(getActivity(), "moblie_bt_code", "string"));
            vcSms.getButton().setEnabled(true);

        } else {
            vcSms.getButton().setText(time + "s");
            vcSms.getButton().setEnabled(false);
        }
    }

    private void changeTimeNum() {
        if (!TimeDownUtils.isRunning()) {
            TimeDownUtils.start(new TimeDownUtils.TimeCallback() {
                @Override
                public void onTime(int time) {
                    Message msg = new Message();
                    msg.what = 101;
                    msg.obj = time;
                    mHandler.sendMessage(msg);
                }
            });
        } else {
            TimeDownUtils.resetCallback(new TimeDownUtils.TimeCallback() {
                @Override
                public void onTime(int time) {
                    Message msg = new Message();
                    msg.what = 101;
                    msg.obj = time;
                    mHandler.sendMessage(msg);
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        if (v == null) {
            return;
        }
        switch ((Integer) v.getTag()) {
            case ACTION_BACK:
                Fragment selectAccountLoginFragment = FragmentUtils.getJmSkin8Fragment(getActivity(), FragmentUtils.SDK_SELECT_ACCOUNT_TAG);
                replaceFragmentToActivity(getFragmentManager(), selectAccountLoginFragment, AppConfig.resourceId(getActivity(), "content", "id"));
                break;
            case ACTION_SEND:
                getVerifyCode();
                break;
            case ACTION_LOGIN:
                callLoginOrRegister();
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (TimeDownUtils.isRunning()) {
            TimeDownUtils.cancel();
            vcSms.getButton().setText(AppConfig.resourceId(getActivity(), "moblie_bt_code", "string"));
            vcSms.getButton().setEnabled(true);
        }

        if (smsTask != null) {
            smsTask.cancel(false);
        }
        if (mobileLoginTask != null) {
            mobileLoginTask.cancel(false);
        }
    }
}
